<template>
  <view class="wrap">
    <image
      class="head-img"
      :src="imgSrc"
      mode="scaleToFill"
      @tap.stop="handleUpload"
    />
    <TnForm
      ref="formRef"
      :model="dynamicValidateForm"
      :rules="formRules"
      label-position="top"
    >
      <TnFormItem label="名称" prop="name">
        <TnInput
          type="textarea"
          v-model="dynamicValidateForm.name"
          placeholder="为你的智能体想一个响亮的名字"
          maxlength="20"
        />
      </TnFormItem>
      <TnFormItem label="简介" prop="description">
        <TnInput
          v-model="dynamicValidateForm.description"
          maxlength="10"
          type="textarea"
          placeholder="介绍你的智能体，吸引更多的人来使用吧"
        />
      </TnFormItem>
      <TnFormItem label="配置信息" prop="configInfo">
        <TnInput
          type="textarea"
          maxlength="500"
          v-model="dynamicValidateForm.configInfo"
          placeholder="描述你想创建的智能体，包括它的作用和特点，以及它生成结果的预期"
        />
      </TnFormItem>
      <TnButton @tap.stop="addDomain">添加问题</TnButton>
      <TnFormItem
        label="推荐问题"
        prop="username"
        v-for="(domain, index) in dynamicValidateForm.domains"
        :prop="'domains.' + index + '.value'"
        :key="domain.key"
        :rules="{
          required: true,
          message: '推荐问题不能为空',
          trigger: 'blur',
        }"
      >
        <TnInput
          v-model="domain.value"
          type="textarea"
          placeholder="请输入问题"
          maxlength="500"
          style="margin-bottom: 30rpx"
        >
          <template #suffix>
            <TnButton @tap.stop="removeDomain(domain)">x</TnButton>
          </template>
        </TnInput>
      </TnFormItem>
    </TnForm>
    <view class="tn-mt tn-flex-center" style="margin-top: 120rpx">
      <TnButton size="xl" @click="showPopupDialog">
        {{ isUpdate ? '发布智能体' : '发布智能体' }}
      </TnButton>
    </view>

    <TnPopup
      v-model="showPopup"
      open-direction="bottom"
      radius="22"
      close-btn
      @close="closePopup"
    >
      <view class="popup-box">
        <view class="set-title">设置权限</view>
        <view class="radio-box">
          <TnRadioGroup v-model="is_private" active-color="#876fd1">
            <TnRadio :label="true">
              <image
                class="radio-img"
                mode="widthFix"
                src="@/static/imgs/lock_icon.png"
              />
              <view class="radio-text"> 私密.仅自己可见</view>
            </TnRadio>
            <TnRadio :label="false">
              <image
                class="radio-img"
                mode="widthFix"
                src="@/static/imgs/user_icon.png"
              />
              <view class="radio-text"> 分享.提交到智能体中心 </view>
            </TnRadio>
          </TnRadioGroup>
        </view>
        <view style="height: 50rpx"></view>
        <view class="okBtn">
          <TnButton size="xl" @click="submitForm" style="margin-top: 150rpx">
            确认发布
          </TnButton></view
        >
      </view>
    </TnPopup>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import TnForm from '@tuniao/tnui-vue3-uniapp/components/form/src/form.vue'
import TnFormItem from '@tuniao/tnui-vue3-uniapp/components/form/src/form-item.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { getQuestionsById, submitAgents, updateAgent } from '@/services/api'
import type { FormRules, TnFormInstance } from '@tuniao/tnui-vue3-uniapp'
import { onLoad } from '@dcloudio/uni-app'
import { tnNavBack } from '@tuniao/tnui-vue3-uniapp/utils'

const formRef = ref<TnFormInstance>()
const showPopup = ref(false)
const is_private = ref(true)
const imgSrc = ref('../../static/imgs/edit_head.jpg')
const isUpdate = ref(false)
const agentDetial = ref({} as any)
const dynamicValidateForm = reactive({
  name: '',
  description: '',
  configInfo: '',
  domains: [
    {
      value: '',
    },
    {
      value: '',
    },
    {
      value: '',
    },
  ],
})
onLoad((option: any) => {
  console.log(option)
  if (option.item) {
    uni.setNavigationBarTitle({
      title: '编辑智能体',
    })
    isUpdate.value = true
    console.log(JSON.parse(option.item))
    agentDetial.value = JSON.parse(option.item)
    console.log(agentDetial.value)
    dynamicValidateForm.name = agentDetial.value.name
    dynamicValidateForm.description = agentDetial.value.description
    dynamicValidateForm.configInfo = agentDetial.value.configInfo
    imgSrc.value = agentDetial.value.picture
    is_private.value = agentDetial.value.is_private
    getQuestions(agentDetial.value.id)
    // dynamicValidateForm.value.description = item.description
    // dynamicValidateForm.value.description = item.description
  }
})
//获取问题列表
const getQuestions = (id) => {
  getQuestionsById(id).then((res) => {
    const { code, data } = res
    if (code === 0) {
      dynamicValidateForm.domains = data.map((item) => {
        return { value: item }
      })
    }
    console.log(dynamicValidateForm.domains)
  })
}
// 规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入名称', trigger: ['change', 'blur'] },
    // {
    //   pattern: /^[\w-]{4,16}$/,
    //   message: '请输入4-16位英文、数字、下划线、横线',
    //   trigger: ['change', 'blur'],
    // },
  ],
  description: [
    { required: true, message: '请输入简介', trigger: ['change', 'blur'] },
  ],
  configInfo: [
    { required: true, message: '请输入配置信息', trigger: ['change', 'blur'] },
  ],
}

const handleUpload = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: function (chooseImageRes) {
      const tempFilePaths = chooseImageRes.tempFilePaths
      uni.uploadFile({
        url: 'https://hr.xming-ai.com/xm/platform/file_upload',
        filePath: tempFilePaths[0],
        name: 'file',
        success: (res) => {
          let data = JSON.parse(res.data)
          if (data.code === 0) {
            imgSrc.value = data.data.file_url
          }
        },
      })
    },
  })
}

const showPopupDialog = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      showPopup.value = true
    } else {
      // uni.showToast({
      //   title: '表单校验失败',
      //   icon: 'none',
      // })
    }
  })
}
const closePopup = () => {
  is_private.value = true
}

// const submitForm = () => {
//   let questions = dynamicValidateForm.domains.map((item) => {
//     return item.value
//   })
//   // delete dynamicValidateForm.domains
//   let params = {
//     name: dynamicValidateForm.name,
//     configInfo: dynamicValidateForm.configInfo,
//     description: dynamicValidateForm.description,
//     is_private: is_private.value,
//     questions: questions,
//     picture: imgSrc.value,
//   }
//   if (isUpdate.value) {
//     params.id = agentDetial.value.id
//     updateAgent(params).then((res) => {
//       const { code, data } = res
//       if (code === 0) {
//         // showPopupDialog()
//         uni.showToast({
//           title: '编辑成功',
//           duration: 1000,
//         })
//         setTimeout(() => {
//           tnNavBack()
//         }, 1000)
//         // tnNavPage('/home-page/agent/list')
//       }
//     })
//   } else {
//     submitAgents(params).then((res) => {
//       const { code, data } = res
//       if (code === 0) {
//         // showPopupDialog()
//         uni.showToast({
//           title: '提交成功',
//           duration: 1000,
//         })
//         setTimeout(() => {
//           tnNavBack()
//         }, 1000)
//         // tnNavPage('/home-page/agent/list')
//       }
//     })
//   }
// }
// 假设动态验证表单和其他所需函数及变量均已正确定义

// 封装成功提示和导航逻辑
const showSuccessToastAndNavigate = (navigateFunction, duration = 1000) => {
  uni.showToast({
    title: '提交成功',
    duration: duration,
  })
  setTimeout(() => {
    navigateFunction()
  }, duration)
}

const handleError = (error) => {
  // 处理错误，例如显示错误信息
  console.error('请求发生错误:', error)
}

const submitForm = async () => {
  try {
    // 验证输入
    if (!dynamicValidateForm || !dynamicValidateForm.name) {
      throw new Error('表单数据不完整')
    }

    let questions = dynamicValidateForm.domains.map((item) => item.value)
    let params = {
      name: dynamicValidateForm.name,
      configInfo: dynamicValidateForm.configInfo,
      description: dynamicValidateForm.description,
      is_private: is_private.value, // 确保is_private已正确定义
      questions: questions,
      picture: imgSrc.value, // 确保imgSrc已正确定义且值有效
    }

    if (isUpdate.value) {
      if (!agentDetial.value || !agentDetial.value.id) {
        throw new Error('详情数据不完整')
      }
      params.id = agentDetial.value.id
      const res = await updateAgent(params)
      if (res.code === 0) {
        showSuccessToastAndNavigate(tnNavBack, 1000)
      } else {
        handleError(res)
      }
    } else {
      const res = await submitAgents(params)
      if (res.code === 0) {
        showSuccessToastAndNavigate(tnNavBack, 1000)
      } else {
        handleError(res)
      }
    }
  } catch (error) {
    handleError(error)
  }
}
const addDomain = () => {
  if (dynamicValidateForm.domains.length < 10) {
    dynamicValidateForm.domains.push({
      value: '',
      key: Date.now(),
    })
    console.log(dynamicValidateForm.domains)
  } else {
    uni.showToast({
      title: '最多添加十条推荐问题',
      duration: 1000,
      icon: 'none',
    })
  }
}

const removeDomain = (item) => {
  if (dynamicValidateForm.domains.length > 1) {
    var index = dynamicValidateForm.domains.indexOf(item)
    if (index !== -1) {
      dynamicValidateForm.domains.splice(index, 1)
    }
  } else {
    uni.showToast({
      title: '最少保留一个推荐问题',
      duration: 1000,
      icon: 'none',
    })
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding: 40rpx 30rpx;
  width: 90%;
  margin: 0 5%;
}
.head-img {
  width: 160rpx;
  height: 160rpx;
  margin: 0 auto;
  // border-radius: 50%;
  border-radius: 20rpx;
  display: block;
  margin-bottom: 40rpx;
}
.radio-img {
  width: 50rpx;
  border-radius: 50%;
  vertical-align: middle;
}
.popup-box {
  padding: 40rpx;
}
.set-title {
  font-family: 'tuniao-xiaowei';
  font-size: 30rpx;
  color: #666;
}
.radio-box {
  margin: 20rpx 0;
}
.radio-text {
  font-family: 'tuniao-xiaowei';
  vertical-align: middle;
  display: inline-block;
  margin-left: 10rpx;
}
.okBtn {
  display: flex;
  justify-content: center;
}
</style>
